package cn.edu.nju.oraldefense.action;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.json.annotations.JSON;

import cn.edu.nju.oraldefense.model.Defense;
import cn.edu.nju.oraldefense.model.Graduate;
import cn.edu.nju.oraldefense.model.Teacher;
import cn.edu.nju.oraldefense.service.DefenseService;
import cn.edu.nju.oraldefense.service.GraduateService;
import cn.edu.nju.oraldefense.service.TeacherService;

import com.opensymphony.xwork2.ActionSupport;

public class DefenseAssignAction extends ActionSupport {

	private DefenseService defenseService;
	private GraduateService graduateService;
	private TeacherService teacherService;

	private boolean success;

	@JSON(serialize = false)
	public DefenseService getDefenseService() {
		return defenseService;
	}

	@Resource
	public void setDefenseService(DefenseService defenseService) {
		this.defenseService = defenseService;
	}

	@JSON(serialize = false)
	public GraduateService getGraduateService() {
		return graduateService;
	}

	@Resource
	public void setGraduateService(GraduateService graduateService) {
		this.graduateService = graduateService;
	}

	@JSON(serialize = false)
	public TeacherService getTeacherService() {
		return teacherService;
	}

	@Resource
	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String execute() {
		List<Teacher> teacherList = teacherService.getAll();
		List<Graduate> graduateList = graduateService.getAll();
		int teacherCount = teacherList.size();
		for(Graduate graduate:graduateList) {
			if(graduate.getTeacher()==null)
				return SUCCESS;
			if(graduate.getPaper()!=null&&graduate.getPaper().getState()==1) {
				Teacher[] tList = new Teacher[3]; 
				tList[0]=graduate.getTeacher();
				
				int tutorIndex = teacherList.indexOf(tList[0]);
				tList[1] = teacherList.get((tutorIndex+1)%teacherCount);
				tList[2] = teacherList.get((tutorIndex+2)%teacherCount);
				
				for (int i = 0; i < tList.length; i++) {
					Defense defense = new Defense();
					Calendar c = Calendar.getInstance();
					c.add(Calendar.DATE, 10);
					defense.setTime(c.getTime());
					defense.setTeacher(tList[i]);
					defense.setGraduate(graduate);
					defenseService.addDefense(defense);
				}
			}
			success = true;
		}
		return SUCCESS;
	}
}
